<?php
class AlipayModule{
	function payurl($txn=null) {
		global $_G;
		$ecm = unserialize(decrypt($_G['settings']['payment']['alipay']));
		
		 $args = array(
            'service'           => $ecm['server'],
            'partner'           => $ecm['apartner'],
            '_input_charset'    => CHARSET,
            'notify_url'        => BASE_URL.'payment.php?f=notify&type=alipay',
            'return_url'        => BASE_URL.'payment.php?f=result&type=alipay',

            'subject' 		=> $txn['subject']?$txn['subject']:$_G['settings']['sitename'],
			//'body' 			=> $_G['settings']['sitename'],
            'out_trade_no'      => $txn['txnid'],
            'price'             => $txn['gross']?$txn['gross']:0.01,  
            'quantity'          => 1,
            'payment_type'      => 1,
            
            'seller_email'      => $ecm['aacount']
        );
		if($ecm['server']=='create_direct_pay_by_user') {
			$args['service'] = 'create_direct_pay_by_user';
		} else {
			$args['logistics_type'] = 'EXPRESS';
			$args['logistics_fee'] = 0;
			$args['logistics_payment'] = 'SELLER_PAY';
		}
		
	    ksort($args);
		$urlstr = $sign = '';
		foreach($args as $key => $val) {
			$sign .= '&'.$key.'='.$val;
			$urlstr .= $key.'='.rawurlencode($val).'&';
		}
		$sign = substr($sign, 1);
		$sign = md5($sign.$ecm['acode']);
		return 'https://www.alipay.com/cooperate/gateway.do?'.$urlstr.'sign='.$sign.'&sign_type=MD5';
	}

	function notify() {
		global $_G;
		if(!empty($_POST)) {//只接收POST来的数值
			$notify = $_POST;
			$is_notify = TRUE;//notify_url 异步通过
		} elseif(!empty($_GET)) {
			$notify = $_GET;
			$is_notify = FALSE;//return_url 异步通过
		} else {
			exit('Access Denied');
		}
		$ecm = unserialize(decrypt($_G['settings']['payment']['alipay']));
		//去除不参与签名的参数
        unset($notify['sign_type'], $notify['order_id'], $notify['type'], $notify['f']);
		
		//校验来路是否正确
		$check = TRUE;
		$responseTxt = $this->getHttpResponse("http://notify.alipay.com/trade/notify_query.do?partner=".$ecm['apartner']."&notify_id=".$notify['notify_id']);
		if(!preg_match("/true$/i",$responseTxt)){
			$check = FALSE;
		}
		ksort($notify);
		$sign = '';
		foreach($notify as $key => $val) {
			if($key != 'sign') $sign .= "&$key=$val";
		}
		if($notify['sign'] != md5(substr($sign,1).$ecm['acode'])) {
			$check = FALSE;
		}
		
		//验证订单号及订单金额是否相符
		switch ( $notify['trade_status'] ) {
			case 'WAIT_BUYER_PAY'://该判断表示买家已在支付宝交易管理中产生了交易记录，但没有付款
				$status = 0;
				break;
			case 'WAIT_SELLER_SEND_GOODS'://买家已付款，等待卖家发货
				$status = 1;
				break;
			case 'WAIT_BUYER_CONFIRM_GOODS'://卖家已发货，等待买家确认
				$status = 1;
				break;
			case 'TRADE_FINISHED'://该判断表示买家已经确认收货，这笔交易完成
				$status = 1;
				break;
			case 'TRADE_SUCCESS'://支付成功
				$status = 1;
				break;
			case 'TRADE_CLOSED'://交易关闭
				$status = 0;
				break;
			default://1 订单在系统中已经生成,等待系统确认,0等待买家付款
				$status = 0;	
			}
			
			if($notify['refund_status'] == 'REFUND_SUCCESS'){
				//退款成功，取消交易
				$status = 9;
			}
			
			return array(
				'type'	=> $is_notify,
				'check'	=> $check,
				'status' 	=> $status,
				'txnid' 	=> $notify['out_trade_no'],
				'price' 	=> ($ecm['service']!='create_direct_pay_by_user') && $notify['price'] ? $notify['price'] : $notify['total_fee'],
				'trade_no'	=> $notify['trade_no'],
				);	
	}
	

	/**
     * 获取远程服务器ATN结果,验证返回URL
     * @param $notify_id 通知校验ID
     * @return 服务器ATN结果
     * 验证结果集：
     * invalid命令参数不对 出现这个错误，请检测返回处理中partner和key是否为空 
     * true 返回正确信息
     * false 请检查防火墙或者是服务器阻止端口问题以及验证时间是否超过一分钟
     */
	function getHttpResponse($url, $input_charset = '', $time_out = "60") {
		$urlarr     = parse_url($url);
		$errno      = "";
		$errstr     = "";
		$transports = "";
		$responseText = "";
		if($urlarr["scheme"] == "https") {
			$transports = "ssl://";
			$urlarr["port"] = "443";
		} else {
			$transports = "tcp://";
			$urlarr["port"] = "80";
		}
		$fp=fsockopen($transports . $urlarr['host'],$urlarr['port'],$errno,$errstr,$time_out);
		if(!$fp) {
			die("ERROR: $errno - $errstr<br />\n");
		} else {
			if (trim($input_charset) == '') {
				fputs($fp, "POST ".$urlarr["path"]." HTTP/1.1\r\n");
			}
			else {
				fputs($fp, "POST ".$urlarr["path"].'?_input_charset='.$input_charset." HTTP/1.1\r\n");
			}
			fputs($fp, "Host: ".$urlarr["host"]."\r\n");
			fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
			fputs($fp, "Content-length: ".strlen($urlarr["query"])."\r\n");
			fputs($fp, "Connection: close\r\n\r\n");
			fputs($fp, $urlarr["query"] . "\r\n\r\n");
			while(!feof($fp)) {
				$responseText .= @fgets($fp, 1024);
			}
			fclose($fp);
			
			$responseText = trim(stristr($responseText,"\r\n\r\n"),"\r\n");
			
			return $responseText;
		}
	}
	
	function trade_getorderurl($orderid) {
		return 'https://www.alipay.com/trade/query_trade_detail.htm?trade_no='.$orderid;
	}
}